class Solution {
public:
    string sortedString(const string &s) {
        string t = s;
        sort(t.begin(), t.end());
        return t;
    }

    vector<string> anagrams(vector<string> &strs) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (strs.size() <= 1) {
            return vector<string>();
        }

        int n = strs.size();
        vector<pair<string, string> > pairs;
        vector<string> ans;

        for (int i = 0; i < n; ++i) {
            pairs.push_back(make_pair(sortedString(strs[i]),
                                      strs[i]));
        }
        sort(pairs.begin(), pairs.end());

        for (int i = 0; i < n; ) {
            int j = i + 1;
            while (j < n && pairs[i].first == pairs[j].first) {
                ans.push_back(pairs[j].second);
                ++j;
            }
            if (j - i > 1) {
                ans.push_back(pairs[i].second);
            }
            i = j;
        }

        return ans;
    }
};
